﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orange.Logistics.Models;
using System.Data.SqlClient;

namespace Orange.Logistics.Services {

    public interface ISystemService {
        SysUser GetUser(string userId, string userPassword);
        int[] GetRolesByUser(string userId);
        IQueryable<Permission> GetButtons(int[] roles, string menuNo);
        bool ChangePassword();
        void SaveChanges();
    }

    public class SystemService : ISystemService {
        private LogisticsContext db = new LogisticsContext();

        public SysUser GetUser(string userId, string userPassword) {
            return db.SysUsers.SingleOrDefault(u => u.UserId.Equals(userId) && u.UserPassword.Equals(userPassword));
        }

        public int[] GetRolesByUser(string userId) {
            return db.UserRoles.Where(ur => ur.UserID.Equals(userId)).Select(r => r.RoleID).ToArray();
        }

        public IQueryable<Permission> GetButtons(int[] roles, string menuNo) {
            var query = from p in db.Permissions
                        join rp in db.RolePermissions on p.Id equals rp.PermissionID
                        join mp in db.ModulePermissions on rp.PermissionID equals mp.PermissionID
                        join m in db.Modules on mp.ModuleID equals m.Id
                        where roles.Contains(rp.RoleID) && m.ModuleController == menuNo
                        select p;
            return query;
        }


        public bool ChangePassword() {
            throw new NotImplementedException();
        }


        public void SaveChanges() {
            db.SaveChanges();
        }
    }
}
